﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TimeBack : MonoBehaviour
{
    //Stack.peek() 和Stack.pop(）的相同点是 获取栈顶的值，不同点 则是 Stack.peek() 只是获取栈顶的值，而Stack.pop() 是获取栈顶的值然后删除。
    public Stack TimeBackData;           
    public bool CheckKeyUp;
    public bool CheckKey;
    public int TimeBackSpeed = 1;
    SpriteRenderer SpriteRenderer;
    Color color;
    ObjectStage Stage;
    Animator animator;
    Rigidbody2D rb2d;

    
    CharacterController2D cc2D;
    //public AudioSource audio;

    public Queue queue;
    public bool isActioning;   //角色是否是阴影
    public bool isBlacking;  //回溯中
    public GameObject PlayerFactory;

    public GameObject Manget;
    void Start()
    {
        Stage = new ObjectStage();
        SpriteRenderer = GetComponent<SpriteRenderer>();
        color = new Color(100 / 255f, 100 / 255f, 100 / 255f, 1);

        animator = GetComponent<Animator>();
        cc2D = GetComponent<CharacterController2D>();
        rb2d = GetComponent<Rigidbody2D>();

        //TimeBackData = new Stack();
        queue = new Queue();
        PlayerFactory = GameObject.Find("PlayerFactory");
        isActioning = false;
    }

    private void Update()
    {
        if (isActioning)
        {
            rb2d.gravityScale = 0;
        }
        else if (!isActioning)
        {
            rb2d.gravityScale = 1.75f;
        }
        //CheckKey = Input.GetKey(KeyCode.B);//长按b回溯
        //CheckKeyUp = Input.GetKeyUp(KeyCode.B);//松开b停止回溯
        CheckKey = Input.GetKeyDown(KeyCode.F);
        if (isActioning && CheckKey)  //阴影被按下回溯键消失
        {
            if (Manget.activeSelf)  //磁铁被激活中时候才尝试移除位于该角色下的子角色   
            {
                this.gameObject.GetComponentInChildren<Magnet>().obj.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;

                this.gameObject.GetComponentInChildren<Magnet>().RemoveChildren();
            }
            PlayerFactory.GetComponent<playerFactory>().DestroyPlayer(this.gameObject);  //玩家队列中删除这个物体
            DestroyImmediate(this.gameObject);

        }
        if (CheckKey&&!isActioning) {      //检查是否按下了F键
            isActioning = true;  //原物体变为阴影
            //todo改为阴影的颜色

            PlayerFactory.GetComponent<playerFactory>().AddPlayer();
        }
       
        //if (isActioning)
        //{
        //    if (Input.GetKeyDown(KeyCode.Q) || Input.GetKeyDown(KeyCode.UpArrow))
        //    {
        //        AddSpeed();
        //    }
        //    if (Input.GetKeyDown(KeyCode.E) || Input.GetKeyDown(KeyCode.DownArrow))
        //    {
        //        SubSpeed();
        //    }
        //}

        //if (CheckKeyUp)
        //{
        //    Restore();
        //}
    }
    
private void FixedUpdate()
    {
        if (TimeBackSpeed == 0)//停止回溯: 当回溯速度为0
        {
            return;
        }
        if (isActioning)//按下b时回溯
        {   

            Stage = LoadData();
            if (Stage != null)
            {
                ShowData(Stage);
            }
            else {
                if (Manget.activeSelf&& isActioning)  //磁铁被激活中时候才尝试移除位于该角色下的子角色   
                {
                    if (this.gameObject.GetComponentInChildren<Magnet>().obj)
                    {
                        this.gameObject.GetComponentInChildren<Magnet>().obj.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
                    }
                    this.gameObject.GetComponentInChildren<Magnet>().RemoveChildren();

                   
                }
                PlayerFactory.GetComponent<playerFactory>().DestroyPlayer(this.gameObject);  //玩家队列中删除这个物体
                DestroyImmediate(this.gameObject);
            }
            //audio.pitch = -1;
        }

        //if(Player_old.activeSelf)//记录回溯: 当 old player激活时取消
        //{
        if(!isActioning)   //如果不是阴影的话为就存储数据
            SaveData();
    }

    void ShowData(ObjectStage ObjectStage) // 改变人物状态
    {
        //rb2d.simulated = false;
        //animator.enabled = false;
        transform.position = ObjectStage.position;
        SpriteRenderer.sprite = ObjectStage.sprite;
        SpriteRenderer.color = color;
        transform.localScale = new Vector3(ObjectStage.isRight ? 1 : -1, 1, 1);
        rb2d.velocity = ObjectStage.velocity;
        Manget.SetActive(ObjectStage.isEnable);
        Manget.transform.rotation = new Quaternion(0, 0, ObjectStage.MangetRota,0);
        Manget.transform.rotation = ObjectStage.MangetDir;
    }
    public void Restore() //恢复
    {
        cc2D.isFacingRight = Stage.isRight;
        animator.enabled = true;
        rb2d.simulated = true;
        rb2d.velocity = Vector2.zero;
        TimeBackSpeed = 1;
        //audio.pitch = 1;
    }
    public void ClearData() //清空队列
    {
        queue.Clear();
    }
    public void SaveData()
    {
        ObjectStage Stage = new ObjectStage();
        Stage.position = transform.position;
        Stage.sprite = SpriteRenderer.sprite;
        Stage.isRight = cc2D.isFacingRight;
        Stage.velocity = rb2d.velocity;
        Stage.isEnable = Manget.activeSelf;
        Stage.MangetRota = Manget.transform.rotation.z;
        Stage.MangetDir = Manget.transform.rotation;
        //TimeBackData.Push(Stage);
        queue.Enqueue(Stage);
    }

    public ObjectStage LoadData() //读取存储
    {
        //if (TimeBackData.Count > 1)
        if (queue.Count > 0)
        {
            for (int i = 1; i < Mathf.Pow(2, TimeBackSpeed - 1); i++)
            {
                //if (TimeBackData.Count > 1)
                if (queue.Count > 0)
                    //TimeBackData.Pop();
                    queue.Dequeue();
                else
                    return (ObjectStage)
                        //TimeBackData.Peek();
                        queue.Peek();
            }
            //if (TimeBackData.Count > 1)
            if (queue.Count > 0)
                return (ObjectStage)
                    //TimeBackData.Pop();
                    queue.Dequeue();
            else
                return (ObjectStage)
                    //TimeBackData.Peek();
                    null;
        }
        else
        {
            return (ObjectStage)
                //TimeBackData.Peek();
                null;
        }
    }


    //用于修改时间倒流的速度
    public void AddSpeed()
    {
        TimeBackSpeed = TimeBackSpeed == 4 ? 4 : TimeBackSpeed + 1;
    }

    public void SubSpeed()
    {
        TimeBackSpeed = TimeBackSpeed == 0 ? 0 : TimeBackSpeed - 1;
    }
}
